//
//  IMB_BrowseViewController.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-4-24.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "IMB_BrowseViewController.h"
#import "BN_CreateContentViewController.h"

@interface IMB_BrowseViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIActionSheetDelegate> {
    // UI
    UIImageView *displayImgView;
    UIImage *thumbnailImage;
    MPMoviePlayerController *moviePlayer;
    // F
    NSDictionary *sendDict;
    NSData *cropVideoData;
    NSURL *cropVideoUrl;
    
    // crop
    AVAssetExportSession *exporter;
}
@property (weak, nonatomic) IBOutlet LRGlowingButton *closeBtn;

@property (weak, nonatomic) IBOutlet UIButton *okBtn;

@end

@implementation IMB_BrowseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.imgInfo = nil;
    self.webURL = nil;
    self.videoOrPhoto = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
    if (IOS7) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
     // 关闭
    [self.closeBtn addTarget:self action:@selector(closeTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.closeBtn.highlightedGlowColor = [UIColor whiteColor];
    self.closeBtn.glowsWhenHighlighted = YES;
    
    // ok
    if ([self.videoOrPhoto isEqualToString:@"video"]) {
        [self.okBtn setImage:[UIImage imageNamed:@"shexiangok"] forState:UIControlStateNormal];
    }else {
        [self.okBtn setImage:[UIImage imageNamed:@"zhaoxiangok"] forState:UIControlStateNormal];
    }
    
    //sendDict
    sendDict = [[NSDictionary alloc]init];
    
    // 底部UI
    // 显示图片
    displayImgView = [[UIImageView alloc]init];
    if (SCREEN_HEIGHT <= 480) {
        displayImgView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_WIDTH-20);
        self.bottomView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-119, SCREEN_WIDTH, 119);
        self.okBtn.frame = CGRectMake((SCREEN_WIDTH-73)/2, (119-73)/2, 73, 73);
    }else {
        displayImgView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_WIDTH);
    }
    [self.view addSubview:displayImgView];
    
    if (self.webURL) {
        
        // 播放小按钮
        UIImageView *playImgView = [[UIImageView alloc]initWithFrame:CGRectMake((displayImgView.frame.size.width-80)/2, (displayImgView.frame.size.height-80)/2, 80, 80)];
        playImgView.image = [UIImage imageNamed:@"bofang"];
        [displayImgView addSubview:playImgView];
        
        // cropVideo
        if (self.isLocal) {
            [self goLoadWebView];
        }else {
            [SVProgressHUD showWithStatus:@"视频加载中..." maskType:SVProgressHUDMaskTypeBlack];
            // 保存视频
            // [self toSaveVideo:self.webURL];
            [self cropVideo:self.webURL];
        }
    }else {
        [self cropImg];
    }
}

#pragma mark
#pragma mark 视频截取 或 加载图片
- (void)cropVideo:(NSURL *)url {
    // output file
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:Baby_Local_Video]) {
        [fileManager createDirectoryAtPath:Baby_Local_Video withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString* outputPath = [Baby_Local_Video stringByAppendingPathComponent:@"result.mp4"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:outputPath])
        [[NSFileManager defaultManager] removeItemAtPath:outputPath error:nil];
    
    // input file
    AVAsset* asset = [AVAsset assetWithURL:url];
    AVMutableComposition *composition = [AVMutableComposition composition];
    [composition  addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    
    // input clip
    AVAssetTrack *clipVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
    
    // make it square
    AVMutableVideoComposition* videoComposition = [AVMutableVideoComposition videoComposition];
    videoComposition.renderSize = CGSizeMake( 320, 320);
    videoComposition.frameDuration = CMTimeMake(1, 320);
    
    AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30) );
    
    // rotate to portrait
    AVMutableVideoCompositionLayerInstruction* transformer = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:clipVideoTrack];
    CGAffineTransform t1 = CGAffineTransformMakeTranslation(clipVideoTrack.naturalSize.height, -(clipVideoTrack.naturalSize.width - clipVideoTrack.naturalSize.height) /2 );
    CGAffineTransform t2 = CGAffineTransformRotate(t1, M_PI_2);
    
    CGAffineTransform finalTransform = t2;
    [transformer setTransform:finalTransform atTime:kCMTimeZero];
    instruction.layerInstructions = [NSArray arrayWithObject:transformer];
    videoComposition.instructions = [NSArray arrayWithObject: instruction];
    
    // export
    exporter = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality] ;
    exporter.videoComposition = videoComposition;
    exporter.outputURL = [NSURL fileURLWithPath:outputPath];
    exporter.outputFileType = AVFileTypeMPEG4;
    [exporter exportAsynchronouslyWithCompletionHandler:^(void){
        NSLog(@"视频截取成功!");
        dispatch_async(dispatch_get_main_queue(), ^{
            [self cancelHint];
        });
        NSString *encodeFinishedPath = [NSString stringWithFormat:@"file://localhost/private%@",outputPath];
        cropVideoUrl = [NSURL URLWithString:encodeFinishedPath];
        self.webURL = cropVideoUrl;
        [self goLoadWebView];
    }];
}

// 加载视频
- (void)goLoadWebView {
    
    // 视频的话，创建内容页cameraAffirmDic 为视频的data和缩略图
    NSData *videoData = nil;
    
    videoData = [NSData dataWithContentsOfURL:self.webURL];
    
    // 选取缩略图
    displayImgView.userInteractionEnabled = YES;
    displayImgView.backgroundColor = APP_OBJECT_GRAY_COLOR;
    UITapGestureRecognizer *bofangTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bofangVideoTapped:)];
    [displayImgView addGestureRecognizer:bofangTap];
    displayImgView.clipsToBounds = YES;
    displayImgView.contentMode = UIViewContentModeScaleAspectFill;
    
    if (self.isLocal) {
        displayImgView.image = [IMB_BrowseViewController thumbnailImageForVideo:self.webURL atTime:100];
        thumbnailImage = [IMB_BrowseViewController thumbnailImageForVideo:self.webURL atTime:100];
        sendDict = @{@"fileData": videoData,@"fileImg":@[thumbnailImage],@"fileType":@"0"};
    }else {
        NSString *XHCameraModeVideo = ALAssetTypeVideo;
         [self updateLibraryButtonWithCameraMode:XHCameraModeVideo didFinishcompledBlock:^(UIImage *thumbnail) {
         if (thumbnail) {
         // UI
         if (displayImgView) {
             displayImgView.image = thumbnail;
             thumbnailImage = thumbnail;
         }
         sendDict = @{@"fileData": videoData,@"fileImg":@[thumbnailImage],@"fileType":@"0"};
         }else {
             NSLog(@"没有视频");
         }
         }];
    }
}

- (void)cropImg {
    UIImage *img = self.imgInfo;

    // 判断是横屏还是竖屏
    switch (self.screenDirectionValue) {
        case 1:
            img = [img rotateImageByAngle:@"90"];
            break;
        case 2:
            img = [img rotateImageByAngle:@"0"];
            break;
        case 3:
            img = [img rotateImageByAngle:@"180"];
            break;
        default:
            break;
    }
    
    UIImage *newImg = [self cutCenterImage:img size:CGSizeMake(SCREEN_WIDTH+200, SCREEN_WIDTH+200)];
    UIImageView *disPimgView = [[UIImageView alloc]init];
    if (SCREEN_HEIGHT <= 480) {
        disPimgView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_WIDTH-20);
    }else {
        disPimgView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_WIDTH);
    }
    disPimgView.image = newImg;
    disPimgView.clipsToBounds = YES;
    disPimgView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:disPimgView
     ];
    sendDict = @{@"fileData": @"无",@"fileImg":@[newImg],@"fileType":@"1"};
}

#pragma mark
#pragma mark Action
/*
// 缩放图片
- (UIImage*)OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);  //size 为CGSize类型，即你所需要的图片尺寸
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;   //返回的就是已经改变的图片
}*/

- (IBAction)okBtn:(id)sender {
    IMB_SaveCameraInfo *saveCameraInfo = [IMB_SaveCameraInfo sharedSaveCameraInfo];
    saveCameraInfo.cameraDict = sendDict;
    [self dismissViewControllerAnimated:NO completion:^{
        [[NSNotificationCenter defaultCenter]postNotificationName:@"K_DIY_CAMERA_VC" object:nil];
    }];
}

- (void)closeTapped:(UIButton *)tap {
    [self releaseResource];
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)bofangVideoTapped:(UITapGestureRecognizer *)tapGestureRecognizer {
    moviePlayer = [[MPMoviePlayerController alloc]initWithContentURL:self.webURL];
     moviePlayer.controlStyle = MPMovieControlStyleNone;
    if (SCREEN_HEIGHT <= 480) {
        moviePlayer.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH-20);

    }else {
        moviePlayer.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH);
    }
     [moviePlayer prepareToPlay];
     [displayImgView addSubview:moviePlayer.view];
}

#pragma mark

#pragma mark 工具方法
// 视频缩略图
+ (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    return thumbnailImage;
}

+ (UIImage *)image:(UIImage *)image rotation:(UIImageOrientation)orientation
{
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    switch (orientation) {
        case UIImageOrientationLeft:
            rotate = M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = 0;
            translateY = -rect.size.width;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationRight:
            rotate = 3 * M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = -rect.size.height;
            translateY = 0;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationDown:
            rotate = M_PI;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = -rect.size.width;
            translateY = -rect.size.height;
            break;
            
        default:
            rotate = 0.0;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = 0;
            translateY = 0;
            break;
            
    }
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    CGContextScaleCTM(context, scaleX, scaleY);
    
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    return newPic;
}

// 根据size截取图片中间矩形区域的图片 这里的size是正方形
- (UIImage *)cutCenterImage:(UIImage *)image size:(CGSize)size{
    CGSize imageSize = image.size;
    CGRect rect;
    //根据图片的大小计算出图片中间矩形区域的位置与大小
    if (imageSize.width > imageSize.height) {
        float leftMargin = (imageSize.width - imageSize.height) * 0.5;
        rect = CGRectMake(leftMargin, 0, imageSize.height, imageSize.height);
    }else{
        float topMargin = (imageSize.height - imageSize.width) * 0.5;
        rect = CGRectMake(0, topMargin, imageSize.width, imageSize.width);
    }
    
    CGImageRef imageRef = image.CGImage;
    //截取中间区域矩形图片
    CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);
    
    UIImage *tmp = [[UIImage alloc] initWithCGImage:imageRefRect];
    CGImageRelease(imageRefRect);
    
    UIGraphicsBeginImageContext(size);
    CGRect rectDraw = CGRectMake(0, 0, size.width, size.height);
    [tmp drawInRect:rectDraw];
    // 从当前context中创建一个改变大小后的图片
    tmp = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    return tmp;
}

// 从相册中抽出最后一张图片
- (void)updateLibraryButtonWithCameraMode:(NSString *)cameraMode didFinishcompledBlock:(void (^)(UIImage *thumbnail))compled {
    __block NSString *assetPropertyType = nil;
    __block NSMutableArray *assets = [[NSMutableArray alloc] init];
    //    if (cameraMode == XHCameraModePhoto) {
    //        assetPropertyType = [ALAssetTypePhoto copy];
    //    } else if (cameraMode == XHCameraModeVideo) {
    //        assetPropertyType = [ALAssetTypeVideo copy];
    //    }
    assetPropertyType = cameraMode;
    
    void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
    {
        if (group == nil)
        {
            return;
        }
        *stop = YES;
        
        __block int num = 0;
        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
         {
             if(result == nil)
             {
                 return;
             }
             __block ALAsset *assetResult = result;
             num++;
             NSInteger numberOf = [group numberOfAssets];
             
             NSString *al_assetPropertyType = [assetResult valueForProperty:ALAssetPropertyType];
             if ([al_assetPropertyType isEqualToString:assetPropertyType]) {
                 [assets addObject:assetResult];
             }
             
             if (num == numberOf) {
                 UIImage *img = [UIImage imageWithCGImage:[[assets lastObject] thumbnail]];
                 dispatch_async(dispatch_get_main_queue(), ^{
                     if (compled) {
                         compled(img);
                     }
                 });
             }
         }];
    };
    
    // Group Enumerator Failure Block
    void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            UIImage *img = [UIImage imageNamed:@"photo_Library.png"];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (compled) {
                    compled(img);
                }
            });
        });
    };
    // Enumerate Albums
    ALAssetsLibrary *library_ = [[ALAssetsLibrary alloc] init];
    [library_ enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
                            usingBlock:assetGroupEnumerator
                          failureBlock:assetGroupEnumberatorFailure];
}

- (void)toSaveVideo:(NSURL *)url {
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        
        ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
        [assetLibrary writeVideoAtPathToSavedPhotosAlbum:url
                                         completionBlock:
         ^(NSURL *assetURL, NSError *error) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 NSString *title;
                 NSString *message;
                 if (error != nil) {
                     title = @"保存视频失败";
                     message = [error localizedDescription];
                 }
                 else {
                     title = @"保存视频成功";
                     message = nil;
                 }
                 // 视频保存到本地以后，开始截取视频
                 [self cropVideo:self.webURL];
             });
         }];
    });
}

#pragma mark 资源

// 取消SVP
- (void)cancelHint {
    [SVProgressHUD dismiss];
}

- (void)releaseResource {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"K_DIY_CAMERA_VC" object:nil];
    self.webURL = nil;
    self.imgInfo = nil;
    displayImgView = nil;
}

- (void)dealloc
{
    [self releaseResource];
    NSLog(@"视频、照片浏览界面释放...");
}
@end
